package com.service.purchase;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSONArray;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.InquiryMapper;
import com.dao.purchase.SupplyOfferMapper;
import com.dao.purchase.SupplyOfferMmMapper;
import com.dao.sys.FileDao;
import com.dao.sys.SysUserMapper;
import com.enums.DealModeEnum;
import com.enums.DictEnum;
import com.model.purchase.PurchaseInquiry;
import com.model.purchase.PurchaseProgram;
import com.model.purchase.PurchaseSupplyOffer;
import com.model.purchase.PurchaseSupplyOfferMm;
import com.model.purchase.PurchaseSupplyOfferVO;
import com.model.supply.SupplyUserModel;
import com.model.sys.FileModel;
import com.model.sys.SysDict;
import com.model.sys.SysUser;
import com.service.supply.InfoService;
import com.service.sys.SysDictService;

/**
 * 报价管理
 * 
 * @author chenjun
 *
 */
@Service("purchaseOfferService")
public class OfferService {

	static final Logger logger = LoggerFactory.getLogger(OfferService.class);

	@Autowired
	InfoService infoService;
	@Autowired
	SupplyOfferMapper supplyOfferMapper;
	@Autowired
	SysUserMapper userMapper;
	@Autowired
	SupplyOfferMmMapper supplyOfferMmMapper;
	@Autowired
	InquiryMapper inquiryMapper;

	/**
	 * 查询报价列表
	 * 
	 * @param map
	 * @return
	 */
	public HttpResult selectOfferList(Map<String, Object> map) {
		EasyuiUtils.addPageNum(map);
		EasyuiUtils.addFilter(map);

//		map.put("inqMode", "线下报价");
		SysUser sysUser = SpringMvcUtils.getSysUser();

		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				map.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				map.put("createId", sysUser.getUserid());
			}
		}

		List<PurchaseSupplyOffer> purchaseSupplyOffers = supplyOfferMapper.selectSupplyOfferList(map);

		if (map.get("sortMode") != null && map.get("sortMode").equals(DealModeEnum.split.getValue())) {
			for (PurchaseSupplyOffer purchaseSupplyOffer : purchaseSupplyOffers) {
				purchaseSupplyOffer.setInqOfrUnitPrice(purchaseSupplyOffer.getInqOfrTotalPrice()
						.divide(purchaseSupplyOffer.getInqOfrNum()).setScale(2, RoundingMode.HALF_UP));
			}
			purchaseSupplyOffers = purchaseSupplyOffers.stream()
					.sorted(Comparator.comparing(PurchaseSupplyOffer::getInqOfrUnitPrice)
							.thenComparing(PurchaseSupplyOffer::getInqOfrTime))
					.collect(Collectors.toList());
		}
		if (map.get("sortMode") != null && map.get("sortMode").equals(DealModeEnum.all.getValue())) {
//			for (PurchaseSupplyOffer purchaseSupplyOffer : purchaseSupplyOffers) {
//				purchaseSupplyOffer.setInqOfrUnitPrice(purchaseSupplyOffer.getInqOfrTotalPrice()
//						.divide(purchaseSupplyOffer.getInqOfrNum()).setScale(2, RoundingMode.HALF_UP));
//			}
			purchaseSupplyOffers = purchaseSupplyOffers.stream()
					.sorted(Comparator.comparing(PurchaseSupplyOffer::getInqOfrTotalPrice)
							.thenComparing(PurchaseSupplyOffer::getInqOfrTime))
					.collect(Collectors.toList());
		}

		int count = supplyOfferMapper.selectSupplyOfferListCount(map);
		HttpResult httpResult = new HttpResult();
		httpResult.setRows(purchaseSupplyOffers);
		httpResult.setTotal(count);
		return httpResult;
	}

	/**
	 * 查询报价明细列表
	 * 
	 * @param map
	 * @return
	 */
	public HttpResult selectOfferMmList(String inqId, String infId) {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("inqId", inqId);
		hashMap.put("infId", infId);
		List<PurchaseSupplyOfferMm> purchaseSupplyOfferMms = supplyOfferMmMapper.selectAll(hashMap);

		HttpResult httpResult = new HttpResult();
		httpResult.setRows(purchaseSupplyOfferMms);

		return httpResult;
	}

	/**
	 * 保存报价明细
	 * 
	 * @param map
	 * @return
	 */
	public HttpResult saveOfferMm(PurchaseSupplyOfferVO purchaseSupplyOfferVO) {
		if (purchaseSupplyOfferVO == null || purchaseSupplyOfferVO.getPurchaseSupplyOfferMms() == null) {
			return HttpResult.error("请求参数为空");
		}
		if (purchaseSupplyOfferVO.getInqOfrNum().doubleValue() <= 0
				|| purchaseSupplyOfferVO.getInqOfrTotalPrice().doubleValue() <= 0) {
			return HttpResult.error("报价数量和价格不能为空！");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(purchaseSupplyOfferVO.getInqId());
		if (StringUtils.isNotNull(purchaseInquiry.getInqActualTime())) {
			return HttpResult.error("报价已揭示，不可操作!");
		}
		if (purchaseInquiry.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}
		int result = 0;
		// 主表保存
//		purchaseSupplyOfferVO.setInfId(supplyUserModel.getInfId());
//		purchaseSupplyOfferVO.setInfContact(supplyUserModel.getUserName());
//		purchaseSupplyOfferVO.setInfContactTel(supplyUserModel.getUserTel());		
		result = supplyOfferMapper.update(purchaseSupplyOfferVO);
		// 明细报价保存
		for (PurchaseSupplyOfferMm purchaseSupplyOfferMm : purchaseSupplyOfferVO.getPurchaseSupplyOfferMms()) {
			if ((result += supplyOfferMmMapper.updateByPrimaryKey(purchaseSupplyOfferMm)) == 0) {
				result += supplyOfferMmMapper.insert(purchaseSupplyOfferMm);
			}
		}
		HttpResult httpResult = new HttpResult();

		if (result > 0) {
			httpResult.setData(purchaseSupplyOfferVO);
			httpResult.setMsg(purchaseSupplyOfferVO.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			return httpResult;
		} else {
			return HttpResult.error(purchaseSupplyOfferVO.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
	}

	@Transactional
	public HttpResult backInquiryOffer(String inqId, String infId) {
		if (inqId == null || infId == null) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(inqId);
		if (StringUtils.isNotNull(purchaseInquiry.getInqActualTime())) {
			return HttpResult.error("报价已揭示，不可回退!");
		}

		int result = 0;
		PurchaseSupplyOffer supplyOffer = supplyOfferMapper.load(inqId, infId);
		supplyOffer.setStatus(Global.NO + "");
		result = supplyOfferMapper.update(supplyOffer);

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("回退成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("回退失败！");
		}
		return httpResult;
	}

	/**
	 * 提交报价
	 * 
	 * @param map
	 * @return
	 */
//	public HttpResult commitOffer(PurchaseSupplyOfferVO purchaseSupplyOfferVO) {
//		if (purchaseSupplyOfferVO == null || purchaseSupplyOfferVO.getPurchaseSupplyOfferMms() == null) {
//			return HttpResult.error("请求参数为空");
//		}
//		int result = 0;
//		// 主表保存
//		result = supplyOfferMapper.update(purchaseSupplyOfferVO);
//		// 明细报价保存
//		for (PurchaseSupplyOfferMm purchaseSupplyOfferMm : purchaseSupplyOfferVO.getPurchaseSupplyOfferMms()) {
//			if ((result += supplyOfferMmMapper.updateByPrimaryKey(purchaseSupplyOfferMm)) > 0) {
//				result += supplyOfferMmMapper.insert(purchaseSupplyOfferMm);
//			}
//		}
//
//		if (result > 0) {
//			return HttpResult.ok("保存成功");
//		} else {
//			return HttpResult.error("保存失败");
//		}
//	}

	@Value("${filepath}")
	String basePath;
	@Autowired
	SysDictService sysDictService;
	@Autowired
	FileDao fileDao;

	/**
	 * 导入报价信息
	 * 
	 * @param map
	 * @return
	 */
	public HttpResult importMM(Map<String, Object> map) {
		List<FileModel> fileModels = fileDao.selectList(map);
		if (fileModels == null || fileModels.size() == 0) {
			return HttpResult.error("导入文件不存在!");
		}

		PurchaseSupplyOffer purchaseSupplyOfferVO = supplyOfferMapper.load(map.get("fileRow").toString(),
				map.get("infId").toString());
		if (purchaseSupplyOfferVO.getInqEndTime().compareTo(DateUtils.getCurrentTime()) <= 0) {
			return HttpResult.error("报价已超时，不可操作!");
		}

		List<SysDict> dicList = sysDictService.queryItemByTypeName(DictEnum.taxString);

		FileModel fileModel = fileModels.get(0);
		String fileName = basePath + "/" + fileModel.getFileUrl() + "/" + fileModel.getFileId() + "-"
				+ fileModel.getFileName();
		List<String> errList = new ArrayList<String>();
		EasyExcel.read(fileName, PurchaseSupplyOfferMm.class, new PageReadListener<PurchaseSupplyOfferMm>(dataList -> {
			for (PurchaseSupplyOfferMm demoData : dataList) {
				if (demoData.getPlanId() == null) {
					errList.add("计划编码：" + demoData.getMmDetail() + "为空");
					break;
				}
				PurchaseSupplyOfferMm purchaseSupplyOfferMm = supplyOfferMmMapper.selectByPrimaryKey(
						map.get("infId").toString(), map.get("fileRow").toString(), demoData.getPlanId());
				if (demoData.getInqOfrNum() == null) {
					errList.add("物资：" + demoData.getMmDetail() + "报价数量为空");
					break;
				}
				purchaseSupplyOfferMm.setInqOfrNum(demoData.getInqOfrNum());
				if (demoData.getInqOfrUnitPrice() == null) {
					errList.add("物资：" + demoData.getMmDetail() + "报价单价为空");
					break;
				}
				purchaseSupplyOfferMm.setInqOfrUnitPrice(demoData.getInqOfrUnitPrice());
				purchaseSupplyOfferMm
						.setInqOfrTotalPrice(demoData.getInqOfrNum().multiply(demoData.getInqOfrUnitPrice()));
				purchaseSupplyOfferMm.setInqDeliverDate(demoData.getInqDeliverDate());
				SysDict sysDict = existsDic(demoData.getInqTaxRate(), dicList);
				if (sysDict == null) {
					errList.add("计划编码：" + demoData.getPlanId() + "税率录入不正确");
				} else {
					purchaseSupplyOfferMm.setInqTaxNum(sysDict.getDicValue());
//					BigDecimal taxBigDecimal = new BigDecimal(sysDict.getDicName());
					purchaseSupplyOfferMm.setInqTaxRate(sysDict.getDicName());
				}
				supplyOfferMmMapper.updateByPrimaryKey(purchaseSupplyOfferMm);
			}
		})).sheet().doRead();
		if (errList.size() > 0) {
			HttpResult httpResult = new HttpResult();
			httpResult.setData(errList);
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			return httpResult;
		}
		return HttpResult.ok("导入成功");
	}

	public SysDict existsDic(String dicString, List<SysDict> dicList) {
		SysDict flag = null;
		for (SysDict sysDict : dicList) {
//			BigDecimal taxBigDecimal = new BigDecimal(sysDict.getDicName());
			if (sysDict.getDicName().equals(dicString)) {
				return sysDict;
			}
		}
		return flag;

	}

	public void exportOfferMm(Map<String, Object> queryMap, HttpServletResponse response) {
		SysUser sysUser = SpringMvcUtils.getSysUser();

		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<PurchaseSupplyOfferMm> purchaseSupplyOfferMms = supplyOfferMmMapper.selectAll(queryMap);

		logger.info("exportProgram:{}", purchaseSupplyOfferMms);
		try {
			EasyExcel.write(response.getOutputStream(), PurchaseSupplyOfferMm.class).sheet("模板")
					.doWrite(purchaseSupplyOfferMms);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
